package com.hk.core.data.mongodb.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Setter;
import org.springframework.data.annotation.Transient;
import org.springframework.data.domain.Persistable;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.FieldType;
import org.springframework.data.mongodb.core.mapping.MongoId;
import org.springframework.util.ClassUtils;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author Kevin
 */
@Setter
public abstract class AbstractSnowflakeIdPersistable implements Persistable<Long>, Serializable {

    @MongoId(targetType = FieldType.OBJECT_ID)
    @Field(value = "_id", targetType = FieldType.INT64)
    private Long id;

    @Override
    public Long getId() {
        return id;
    }

    @Override
    @Transient
    @JsonIgnore
    public boolean isNew() {
        return null == getId();
    }

    @Override
    public boolean equals(Object obj) {
        if (null == obj) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!getClass().equals(ClassUtils.getUserClass(obj))) {
            return false;
        }
        var that = (AbstractSnowflakeIdPersistable) obj;
        Long thisId = this.getId();
        return Objects.nonNull(thisId) && thisId.equals(that.getId());
    }

    @Override
    public int hashCode() {
        var hashCode = 17;
        Long thisId = getId();
        hashCode += Objects.isNull(thisId) ? 0 : thisId.hashCode() * 31;
        return hashCode;
    }
}
